import glob,time
from util import get,dump,preprocess_image
from tqdm import tqdm  # tqdm库用于创建进度条
import numpy as np  # numpy库，用于数值计算，简称为np
from sklearn.model_selection import train_test_split
linspace_list = np.linspace(0, 0, 1000)
# 1. 读取配置文件中的信息
train_dir = get("train") # 获取 训练数据路径
char_styles = get("char_styles") # 获取 字符样式列表，注意: 必须是列标
new_size = get("new_size") # 获取 新图像大小元组, 注意: 必须包含h和w
# 2. 生成X,y
X=[]
y=[]
print("# 读取训练数据并进行预处理，")
image_files = [glob.glob(f"{train_dir}/train_{category}*") for category in char_styles]
for i in range(5):
    for element in tqdm(image_files[i], desc=f"处理 {char_styles[i]} 图像", unit="it"):
        label = element.split('_')[1]
        X.append(preprocess_image(element, new_size))
        y.append(char_styles.index(label))
    time.sleep(0.1)
# 3. 分割测试集和训练集
X = np.array(X).astype(float)
y = np.array(y).astype(int)
print("# 将数据按 80% 和 20% 的比例分割")
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2)
# 4. 打印样本维度和类型信息
print("X_train: ", X_train.shape, X_train.dtype)  # 训练集特征的维度和类型
print("X_test: ", X_test.shape, X_test.dtype)  # 测试集特征的维度和类型
print("y_train: ", y_train.shape, y_train.dtype)  # 训练集标签的维度和类型
print("y_test: ", y_test.shape, y_test.dtype)  # 测试集标签的维度和类型
# 5. 序列化分割后的训练和测试样本
obj=(X_train,X_test,y_train,y_test)
objname=["X_train","X_test","y_train","y_test"]
dump(obj,"(X_train,X_test,y_train,y_test)",f'{get("Xy_root")}/Xy')